/**
 *
 * 弹出框选择图片，
 *  作用：上传一张图片，添加对应的描述，进行添加
 *  备注：非纯ui组件，携有部分功能与基础逻辑
 */

import React from "react";
import {Modal,Upload,Icon,Input,Button,message} from 'antd';
import Relay from "react-relay";
import DelQiniuFileMutation from "../mutation/DelQiniuFileMutation" // 删除图片

import classnames from 'classnames';

import {UpLocalLoad,html5Reader,UpLoacalFile} from '../components/FileImgOffLine'

const Item = UpLocalLoad.Item;

export default class A extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible:false,
            text:"",
            fileList:[],  //当前图片文件
            imgSrc:"",  //当前上传图片的url
            alarm:false,  // 格式提示文本

            showLoading:false,   //上传进度条是否显示
            progress:0 ,   //上传的进度

            isUpFile:true,

            left:0,  //拖动x
            top:0   //拖动Y
        };

        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.updataFile = this.updataFile.bind(this);
        this.onFilChange = this.onFilChange.bind(this);
        this.picRemove = this.picRemove.bind(this);

        // 拖动事件
        this.handleMouseDown = this.handleMouseDown.bind(this);
        this.handleMouseUp = this.handleMouseUp.bind(this);
    }

    //验证图片promise
    testImgPromise = (base64)=>{
        return new Promise((resolve,reject)=>{
            // 获取当前文件链接
            let S = base64;
            const {width,height} = this.props.limit;

            // 创建图片构造函数，查看其高度宽度是否符合规则;
            let Img = new Image(); Img.src = S;
            Img.onload = ()=>{
                const w = Img.width,
                    h = Img.height;

                if(width < w || height < h){
                    // 格式无误，执行下一步操作
                    resolve();
                }else{
                    reject();
                }
            }
        })
    };

    ImgCatch(){
        // 小于了规定的尺寸
        this.setState({
            alarm:true
        },()=>{message.error("请仔细阅读图片上传规则");});
    }

    onOk(){
        if(this.state.fileList.length!==0){

            const o = {file:this.state.fileList[0],text:this.state.text,base64:this.state.imgSrc}
            this.props.addFileImg(o);
            this.setState({
                visible:false
            })
            this.clear();
        }else{
            message.error("请上传图片");
        }
    }

    // 删除七牛图片
    picRemove(){
        //下列固定为0，因为list最多只能上传一个，固0
        const name = this.state.fileList[0].response.key;

        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey: name
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {}
                }
            }
        )
    }

    // 清空
    clear(){
        this.setState({
            visible:false,
            text:"",
            imgSrc:"",
            fileList:[],
            left:0,
            top:0,
            alarm:false
        });
        this.handleMouseUp();
    }

    onCancel(){
        // 删除图片
        // this.state.fileList.length !== 0 && this.picRemove();
        this.setState({
            fileList:[],
            isUpFile:true
        });
        this.clear(); //清空状态
    }

    updataFile(file,index,id){
        const date = new Date().getTime();
        return {file:file,token:this.props.token,key:`PackStep_${date}`}
    }

    getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }


    onFilChange(res){
        // 无论哪种情况都把fileList返回给当前状态
        !(function () {
            this.state.fileList = res.fileList;
            this.setState({fileList:this.state.fileList});
        }.bind(this))();

        if(res.file.status === "local"){
            //验证图片格式（宽高） [异步]
            this.getBase64(res.file.originFileObj,(result)=>{
                this.testImgPromise(result).then(()=>{
                    this.setState({
                        imgSrc:result,
                        alarm:false
                    });
                });
                this.testImgPromise(result).catch(()=>{
                    this.ImgCatch();
                    this.setState({
                        fileList:[]
                    })
                })
            });
        }
    }


        // 在uploading 当中显示进度条

        // if(file.status === "uploading"){
        //     if(event){
        //         this.setState({
        //             showLoading:true
        //         },()=>{
        //             // 开始 Progress
        //             const progress = (event.loaded/event.total)*100;
        //             //loaded
        //             //total
        //             this.setState({progress})
        //         })
        //     }
        // }



        //上传失败
        // if(file.status === "error"){
        //     message.error("上传图片失败，请重试");
        // }
        //
        // // 删除图片
        // if(file.status === "removed"){
        //     console.log("删除图片");
        // }
    // }

    // 拖动功能
    handleMouseDown(event) {
        // 禁止点击
        this.state.isUpFile = false;

        let e = event || window.event,
            disX = e.clientX - event.target.offsetLeft,
            disY = e.clientY - event.target.offsetTop;

        document.onmousemove = (event)=>{
            let e = event || window.event;
            this.setState({
                left:(e.clientX - disX),
                top:(e.clientY - disY)
            })
        }
    }

    handleMouseUp(event){
        document.onmousemove = null;
        document.onmouseup = null;
    }

    componentWillMount(){

    }

    handleTextChange = (e)=>{
        this.setState({text:e.target.value})
        if( this.state.text.length >= this.props.TextProps.maxLength ){
            const t = this.state.text;
            this.setState({text:t.slice(0,t.length-1)})
        }
    }


    render() {
        const {uploadPlugin,TextProps} = this.props;
        const {fileList,imgSrc,left,top,text,alarm,isUpFile} = this.state;
        return(
            <Modal
                className="packagSteps_AddImgModal"
                visible={this.state.visible}
                onOk={this.onOk}
                title="上传图片"
                onCancel={this.onCancel}
                maskClosable={false}
            >

                <UpLocalLoad
                    onChange={(res)=>{this.onFilChange(res)}}
                    {...uploadPlugin}
                    isSelect={isUpFile} //是否弹出file系统框
                >
                    <div className="packagSteps_AddImgModal_trigger">
                        {
                            fileList.length !==0 ?
                            <img src={imgSrc}
                                 draggable="false"
                                 alt=""
                                 className="AddImgModal_avatar AddImgModal_avatar_move"
                                 style={{left,top}}
                                 onMouseDown={(e)=>this.handleMouseDown(e)}
                                 onMouseUp={(e)=>this.handleMouseUp(e)}
                                 onMouseLeave={this.handleMouseUp}
                            /> :
                                <div className="AddImgModal_avatar_main">
                                    <Icon type="plus" className="AddImgModal_avatar-uploader-trigger" />
                                    <span> 选择图片 </span>
                                </div>
                        }
                    </div>
                </UpLocalLoad>

                <div>
                    <Input type="textarea"
                           value={text}
                           onChange={this.handleTextChange}
                           {...TextProps}
                           maxLength="50"
                    />
                </div>

                {/*packagSteps_AddImgModal_alarm*/}
                <footer>
                    <p className={classnames({"packagSteps_AddImgModal_alarm":true,"hide":!alarm})}>
                        请您上传大于800*800像素、其大小不超过8M的，BMP、JPEG、JPG、GIF、PNG格式的图片。
                    </p>
                </footer>
            </Modal>
        )
    }

}